/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

const PENDING = 'pending'; //等待
const FULFILLED = 'fulfilled'; //成功
const REJECTED = 'rejected'; //失败

class MyPromise {
  static all(array) {
    const result = [];// 结果数组
    let index = 0; // 执行标记已经执行过确保输出结果顺序一致
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value
        index++
        if (index === array.length) {
          resolve(result)
        }
      }
      array.map((value,i)=>{
        //检测value
        if (value instanceof MyPromise) {
          // Promise 对象
          value.then(v => addData(i, v), r => reject(r))
        } else {
          // 普通值
          addData(i, value)
        }
      })
    })
  }

  static resolve(value) {
    if (value instanceof MyPromise) {
      return value;
    }
    return new MyPromise(resolve => resolve(value))
  }

  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }

  //  Promise 的状态  三个状态 ：等待 成功 失败 不可逆（比如 ：已经是成功状态，则不能在改为失败）
  status = PENDING
  // 成功之后的值
  value = undefined
  // 失败之后的原因
  reason = undefined
  // 记录成功回调
  successCallback = [];
  failCallback = [];
  // 失败之后回调
  resolve = value => {
    // 状态不可逆
    if (this.status !== PENDING) {
      return
    }
    this.status = FULFILLED;// 状态更改为成功
    this.value = value;// 保存成功之后的值
    // 判断成功回调是否存在
    while (this.successCallback.length) {
      this.successCallback.shift()();
    }
  }

  reject = reason => {
    if (this.status !== PENDING) {
      return
    }
    //  装个更改为失败
    this.status = REJECTED
    // 保存失败之后的原因
    this.reason = reason
    // 判断失败回调是否存在
    while (this.failCallback.length) {
      this.failCallback.shift()();
    }
  }

  then(successCallback, failCallback) {
    // 处理 then 的参数
    successCallback = successCallback ? successCallback : v => v
    failCallback = failCallback ? failCallback : r => { throw r }
    // then 方法为了实现链式调用，返回promise方法
    const promise2 = new MyPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        queueMicrotask(() => { //微任务 queueMicrotask 这一块还有点不理解 
          try {
            const x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        })
      } else if (this.status === REJECTED) {
        queueMicrotask(() => {
          try {
            const x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        })
      } else {
        this.successCallback.push(() => {
          queueMicrotask(() => {
            try {
              const x = successCallback(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          })
        })
        this.failCallback.push(() => {
          queueMicrotask(() => {
            try {
              const x = failCallback(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          })
        })
      }
    })

    return promise2
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  // promise2 then方法返回的promise对象
  // x then方法成功的回调函数返回的数据
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))//
  }

  // 判断x是否是promise对象
  if (x instanceof MyPromise) {
    // x 是 promise 对象
    x.then(resolve, reject)
  } else {
    // x 普通值
    resolve(x)
  }
}

MyPromise.prototype.finally = function (callback) {
  return this.then(v => {
    return MyPromise.resolve(callback()).then(() => v)
  }, r => {
    return MyPromise.resolve(callback()).then(() => { throw r })
  })
}

MyPromise.prototype.catch = function (failCallback) {
  return this.then(undefined, failCallback)
}

module.exports = MyPromise